package org.hong.monkey.network.util;

public enum ByteUnit {
    BYTE (1),
    KiB (1024L),
    MiB ((long) Math.pow(1024, 2L)),
    GiB ((long) Math.pow(1024, 3L)),
    TiB ((long) Math.pow(1024, 4L)),
    PiB ((long) Math.pow(1024, 5L));

    private final  long multiplier;

    private ByteUnit(long multiplier) {
        this.multiplier = multiplier;
    }

    public long convertFrom(long d, ByteUnit u) {
        return u.convertTo(d, this);
    }

    public long convertTo(long d, ByteUnit u) {
        if (multiplier > u.multiplier) {
            long ratio = multiplier / u.multiplier;
            if (Long.MAX_VALUE / ratio < d) {
                throw new IllegalArgumentException("Conversion of " + d + " exceeds Long.MAX_VALUE in "
                        + name() + ". Try a larger unit (e.g. MiB instead of KiB)");
            }
            return d * ratio;
        } else
            return d / (u.multiplier / multiplier);
    }

    public double toBytes(long d) {
        if (d < 0)
            throw new IllegalArgumentException("Negative size value, Size must be positive: " + d);
        return d*multiplier;
    }

    public long toKiB(long d) { return convertTo(d, KiB); }
    public long toMiB(long d) { return convertTo(d, KiB); }
    public long toGiB(long d) { return convertTo(d, KiB); }
    public long toTiB(long d) { return convertTo(d, KiB); }
    public long toPiB(long d) { return convertTo(d, KiB); }
}
